package com.redstar.HappyRefresh.manage;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.redstar.HappyRefresh.authority.Authority;
import com.redstar.HappyRefresh.pojo.*;
import com.redstar.HappyRefresh.service.RolePermissionService;
import com.redstar.HappyRefresh.service.RoleService;
import com.redstar.HappyRefresh.service.UserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/authorize/role")
public class RoleManage {

    @Autowired
    private RoleService roleService;
    @Autowired
    private RolePermissionService rolePermissionService;
    @Autowired
    private UserRoleService userRoleService;

    @GetMapping("/treeList")
    @Authority("permission:treeList")
    public List<Tree> treeList() { // 查询权限树，为角色分配权限时需要查询完整的权限树结构
        return roleService.tree();
    }

    @PostMapping("/assignRole")
    @Authority("user:assignRole")
    public Result assignRole(@RequestBody AssignRoleVO assignRoleVO) { // 为用户重新分配角色
        String message = roleService.gaveRole(assignRoleVO);
        if ("success".equals(message)) {
            return Result.succeed().message("分配角色成功");
        } else {
            log.error("assignRole方法：分配角色失败，" + message);
            return Result.fail().message("分配角色失败");
        }
    }

    @GetMapping("/getUserRole/{userId}")
    @Authority("role:getRole")
    public List<Long> getRole(@PathVariable Integer userId) { // 获取用户对应的角色id
        return userRoleService.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId).select(UserRole::getRoleId))
                .stream().map(UserRole::getRoleId).collect(Collectors.toList());
    }

    @GetMapping("/initRole")
    @Authority("role:initRole")
    public List<Map<String, Object>> initRole() { // 初始化角色，查询所有角色的id和名称
        return roleService.list().stream()
                .map(role -> {
                    Map<String, Object> data = new HashMap<>();
                    data.put("value", role.getId());
                    data.put("title", role.getName());
                    return data;
                }).collect(Collectors.toList());
    }


    @GetMapping("/list")
    @Authority("role:list")
    public Result list(BasePage basePage, @RequestParam(required = false) String name) { // 分页查询角色所有信息，用于搜索
        IPage<Role> rolePage = roleService.page(basePage.page(), new LambdaQueryWrapper<Role>().like(!ObjectUtils.isEmpty(name), Role::getName, name));
        return Result.succeed().data(rolePage.getRecords()).count(rolePage.getRecords().size());
    }

    @PostMapping
    @Authority("role:add")
    public Result add(@RequestBody Role role) { // 添加角色
        roleService.save(role);
        return Result.succeed();
    }

    @PutMapping
    @Authority("role:update")
    public Result update(@RequestBody Role role) { // 修改角色
        roleService.updateById(role);
        return Result.succeed();
    }

    @DeleteMapping("/{id}")
    @Authority("role:delete")
    public Result delete(@PathVariable String id) { // 删除角色
        String message = roleService.removeRole(id);
        if ("success".equals(message)) {
            return Result.succeed().message("删除成功");
        } else{
            log.error("delete方法：删除失败，" + message);
            return Result.fail().message("删除失败");
        }
    }

    @PostMapping("/authority")
    @Authority("role:authority")
    public Result authority(@RequestBody AuthorityVO authorityVO) { // 给角色分配权限
        String message = roleService.gavePermission(authorityVO);
        if ("success".equals(message)) {
            return Result.succeed().message("分配权限成功");
        } else {
            log.error("authority方法：分配权限失败，" + message);
            return Result.fail().message("分配权限失败");
        }
    }

    @GetMapping("/getPermission/{id}")
    @Authority("role:getPermission")
    public Integer[] getPermission(@PathVariable Integer id) { // 获取角色权限
        return rolePermissionService.list(new LambdaQueryWrapper<RolePermission>().eq(RolePermission::getRoleId, id).select(RolePermission::getPermissionId))
                .stream().map(RolePermission::getPermissionId).toArray(Integer[]::new);
    }
}

